<template>
  <div class="dashboard-container">
    <div class="dashboard-text">
      <el-card class="tree-card">
        <!-- 头部公司 -->
        <treeTools :tree-node="compent" :is-root="true" @addDepartments="addDepartments" />
        <hr>
        <el-tree :data="treeData" :default-expand-all="true" :props="{label:'name'}">
          <!-- 部门 -->
          <template #default="scoped">
            <treeTools
              :tree-node="scoped.data"
              :is-root="false"
              @delDepartments="getDepartments"
              @addDepartments="addDepartments"
              @editDepartments="editDepartments"
            />
          </template>
        </el-tree>
      </el-card>
      <addDialog ref="dialogAddDept" :visible.sync="showDialog" :node-data="nodeData" @addDepts="getDepartments" /></div>
  </div>
</template>

<script>
// import { mapGetters } from 'vuex'
import treeTools from './components/tree-tools.vue'
import addDialog from './components/addDialog.vue'
import { getDepartments } from '@/api/departments'
// import { listToTreeData } from '@/utils'
export default {
  components: {
    treeTools, addDialog
  },
  data() {
    return {
      compent: {
        name: '江苏传智播客教育科技股份有限公司',
        manager: '负责人',
        id: ''
      },
      treeData: [],
      showDialog: false,
      nodeData: {}
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      const res = await getDepartments()
      console.log(res)
      res.depts.splice(0, 1)
      // this.treeData = listToTreeData(res.depts, '')
      this.treeData = this.listToTreeDataRecursion(res.depts, '')
    // console.log(this.treeData)
    },

    // 递归的方法
    listToTreeDataRecursion(list, topPid) {
      const arr = []
      list.forEach(element => {
        if (element.pid === topPid) {
          // 调用自己,找到 id=pid 的
          const children = this.listToTreeDataRecursion(list, element.id)
          if (children.length > 0) {
            element.children = children
          }
          // console.log(element.children)
          // console.log(element.name)
          arr.push(element)
        }
      })
      // console.log(arr)
      return arr
    },

    addDepartments(nodeData) {
      this.showDialog = true
      this.nodeData = nodeData
    },
    editDepartments(nodeData) {
      // 需要调用子组件的函数进行数据获取
      // 父组件可以给子组件一个 ref 命名
      // 然后通过 this.$refs.xxx.函数名 直接调用
      this.$refs.dialogAddDept.getDepartmentDetail(nodeData.id)
      this.showDialog = true
      this.nodeData = nodeData
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
